package com.easydata.libPlugin.core;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.easydata.libPlugin.core.interfaces.IDataWriter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class AbstractSource extends AbstractNode {
    protected List<IDataWriter> writers = new ArrayList<>();

    public void addWriter(IDataWriter writer) {
        this.writers.add(writer);
    }

    protected void stop() throws Exception {
        this.writers.forEach(IDataWriter::flush);
        this.writers.forEach(IDataWriter::close);
        super.stop();
    }

    final synchronized protected void produce(JSONArray list) throws Exception {

        writers.forEach(w -> {
            try {
                w.write(list);
            } catch (Exception e) {
                this.exception(e);
            }
        });

        this.eventListeners.stream().filter(Objects::nonNull).forEach(evt -> {
            evt.onProduced(this, JSONArray.from(list));
        });
    }

    /// 向后传递数据
    final protected void produce(JSONObject obj) throws Exception {
        this.produce(JSONArray.of(obj));
    }
}
